package uebung03;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

public class NetworkSimulation
{
  private LinkedBlockingQueue<Integer> pipe;
  private Random random = new Random();
  private static String monitor = "";
  
  public NetworkSimulation(int pipeCapacity)
  {
    pipe = new LinkedBlockingQueue<Integer>(pipeCapacity);
  }
  
  class Sender implements Runnable
  {
    public void run()
    {
      for(int i = 0; i<5; i++)
      {
        waitSec();
        try
        {
          int nextRandom = random.nextInt(100);
          pipe.put(nextRandom);
          System.out.println(nextRandom+" wurde gesendet");
        }
        catch (InterruptedException e)
        {
          e.printStackTrace();
        }
      }
    }
  }
  
  class Receiver implements Runnable
  {
    public void run()
    {
      for(int i = 0; i<5; i++)
      {
        waitSec();
        try
        {
          int takenValue = pipe.take();
          System.out.println(takenValue+" wurde empfangen");
        }
        catch (InterruptedException e)
        {
          e.printStackTrace();
        }
      }
    }
  }
  
  public static void main(String[] args)
  {
    NetworkSimulation sim = new NetworkSimulation(1);
    Sender sender = sim.new Sender();
    Receiver receiver = sim.new Receiver();
    
    Thread[] senders = new Thread[2];
    for(Thread t : senders)
    {
      t = new Thread(sender);
      t.start();
    }
    
    Thread[] receivers = new Thread[2];
    for(Thread t : receivers)
    {
      t = new Thread(receiver);
      t.start();
    }
  }
  
  public static void waitSec()
  {
    synchronized(monitor)
    {
      try
      {
        monitor.wait(1000);
      }
      catch (InterruptedException e)
      {
        e.printStackTrace();
      }
    }
  }
}
